const app = getApp()
import { saveFile, createSupplierStoragePage } from '../../api/index.js'
const uploadOss = require('../../utils/upload/uploadImg.js')
import { uuid } from '../../utils/util'

Page({
  data: {
    form: {
      businessLicenseFileIds: [],
      proxyCertificateFileIds: [],
      companyFileIds: [],
    },
    showPop: false,
    businessLicenseFileIds: [],
    proxyCertificateFileIds: [],
    companyFileList: []
  },
  delTempFile ({ detail: { currentTarget: { dataset: { key, item, index } } } }) {
    this.data[`${key}`].splice(index, 1)
    this.setData({
      [`${key}`]: this.data[`${key}`]
    })
  },
  delFile ({ detail: { currentTarget: { dataset: { key, item, index } } } }) {
    this.data.form[`${key}`].splice(index, 1)
    this.setData({
      [`form.${key}`]: this.data.form[`${key}`]
    })
  },
  async againFile ({ detail: { currentTarget: { dataset: { key, item, index } } } }) {
    try {
      let _this = this
      let tempFiles = this.data[`${key}`]
      tempFiles[index].success = ''
        _this.setData({
          [`${key}`]: tempFiles
        })
      const fileUrl = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
      if (fileUrl) {
        const { ResultSet } = await saveFile({
          fileList: [{
            fileSize: item.size,
            fileUrl: fileUrl
          }]
        })
        tempFiles.splice(index, 1)
        _this.data.form[key].push({
          uuid: item.uuid,
          fileId: ResultSet.userData.fileIdList[0].fileId,
          fileUrl: ResultSet.userData.fileIdList[0].fileUrl
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      } else {
        tempFiles[index].success = 1
        _this.setData({
          [`${key}`]: tempFiles
        })
      }
    } catch (err) {
      console.log(err)
    }
  },
  delCompanyFile ({ target: { dataset: { item, index, key } } }) {
    this.data[key].splice(index, 1)
    this.setData({
      [`${key}`]: this.data[key]
    })
  },
  delSuccessFile ({ target: { dataset: { item, index } } }) {
    this.data.form.companyFileIds.splice(index, 1)
    this.setData({
      'form.productManualList': this.data.form.companyFileIds
    })
  },
  async addUpload () {
    let _this = this
    wx.chooseMessageFile({
      count: 9,
      type: 'file',
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data.companyFileList.push(...res.tempFiles)
        _this.setData({
          companyFileList: _this.data.companyFileList
        })
        let tempFiles = _this.data.companyFileList
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            let fileExtension = item.name.split('.')[item.name.split('.').length - 1]
            const fileUrl = await _this.uploadFile(item, 'path', tempFiles, index, _this, 'companyFileList')
            if (fileUrl) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileName: item.name,
                  fileExtension: fileExtension,
                  fileSize: item.size,
                  fileUrl: fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileName: item.name,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                companyFileList: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form.companyFileIds.push(...tempFileList)
        _this.data.form.companyFileIds.forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          companyFileList: tempFiles,
          'form.companyFileIds': _this.data.form.companyFileIds
        })
      }
    })
  },
  addFile ({ target: { dataset: { key } } }) {
    let _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const fileUrl = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (fileUrl) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileUrl: fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form[key].push(...tempFileList)
        _this.data.form[key].forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      }
    })
  },
  uploadFile (item, key, files, index, that, dataKey) {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (fileUrl) => {
          resolve(fileUrl)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  preStep () {
    wx.$nav.navigateBack()
  },
  async nextStep () {
    if (!this.data.form.businessLicenseFileIds.length) {
      wx.showToast({ title: '请上传营业执照！', icon: 'none' })
      return 
    }
    if (!this.data.form.proxyCertificateFileIds.length) {
      wx.showToast({ title: '请上传代理证书！', icon: 'none' })
      return 
    }
    if (!this.data.form.companyFileIds.length) {
      wx.showToast({ title: '请上传公司介绍附件！', icon: 'none' })
      return 
    }
    this.data.form.productPositioning = this.data.form.productPositioning.join(',')
    await createSupplierStoragePage({ ...this.data.form })
    this.setData({
      showPop: true
    })
  },
  onLoad () {
    const { form, dropDown } = app.globalData
    if (dropDown.certificationList.length) {
      this.setData({
        certificationList: dropDown.certificationList
      })
    } else {
      app.globalData.getDropDownCallback = res => {
        this.setData({
          certificationList: app.globalData.dropDown.certificationList
        })
      }
    }
    let newForm = { ...this.data.form, ...form }
    this.setData({ form: newForm })
    // this.getSelectList()
    // this.getAddres()
  },
})
